package com.x2.modular.system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.x2.base.auth.context.LoginContextHolder;
import com.x2.base.consts.ConstantsContext;
import com.x2.base.pojo.page.LayuiPageFactory;
import com.x2.base.pojo.page.LayuiPageInfo;
import com.x2.core.auth.util.SaltUtil;
import com.x2.core.constant.Const;
import com.x2.core.constant.SysTreeNode;
import com.x2.core.constant.factory.ConstantFactory;
import com.x2.core.constant.factory.UserFactory;
import com.x2.core.constant.state.ManagerStatus;
import com.x2.core.exception.enums.BizExceptionEnum;
import com.x2.core.util.BeanContextHolder;
import com.x2.core.util.ToolUtil;
import com.x2.kernel.model.exception.ServiceException;
import com.x2.kernel.model.response.ResponseData;
import com.x2.modular.system.entity.Dept;
import com.x2.modular.system.entity.User;
import com.x2.modular.system.mapper.UserMapper;
import com.x2.modular.system.model.UserBean;
import com.x2.modular.system.utils.UserListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 管理员表 服务实现类
 *
 * @author changpeng
 * @date 2021-01-08
 */
@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Autowired
    private MenuService menuService;
    @Autowired
    private DeptService deptService;

    /**
     * 添加用戶
     *
     * @param user: 条件
     * @return 结果
     * @throws ServiceException
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseData addUser(UserBean user) throws ServiceException {
        // 判断账号是否重复
        if (!ToolUtil.isEmpty(user.getAccount())) {
            User theUser = this.getByAccount(user.getAccount());
            if (theUser != null) {
                return ResponseData.error("账号已存在");
            }
        }
        // 完善账号信息
        String salt = SaltUtil.getRandomSalt();
        String password = SaltUtil.md5Encrypt(ConstantsContext.getDefaultPassword(), salt);
        User newUser = UserFactory.createUser(user, password, salt);
        newUser.setCreateDept(newUser.getDeptId());
        this.save(newUser);
        return ResponseData.success();
    }

    /**
     * 修改用户
     *
     * @author x2
     * @Date 2018/12/24 22:53
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseData editUser(UserBean user) {

        User tmpUser = new User();
        BeanUtils.copyProperties(user, tmpUser);
        this.updateById(tmpUser);
        //触发
        UserListener.fireEvent(tmpUser);
        return ResponseData.success();
    }

    /**
     * 删除用户
     *
     * @param userId: 用户id
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseData deleteUser(Long userId) {
        if (userId.equals(Const.ADMIN_ID)) {
            return ResponseData.error(BizExceptionEnum.CANT_DELETE_ADMIN.getMessage());
        }
        User delUser = this.getById(userId);
        this.baseMapper.setStatus(userId,  ManagerStatus.DELETED.getCode());
        //删除角色人员关联
        UserRoleService userRoleService = BeanContextHolder.getBean(UserRoleService.class);
        userRoleService.deleteByUserId(userId);
        //触发
        UserListener.fireEvent(delUser);
        return ResponseData.success();
    }

    /**
     * 修改用户状态
     *
     * @param userId：用户ID
     * @param status：状态
     * @return
     */
    public int setStatus(Long userId, String status) {
        try {
            return this.baseMapper.setStatus(userId, status);
        } finally {
            //触发
            UserListener.fireEvent(userId);
        }
    }

    /**
     * 修改密码
     *
     * @param oldPassword:    原密码
     * @param newPassword：新密码
     * @return
     */
    public ResponseData changePwd(String oldPassword, String newPassword) {
        Long userId = LoginContextHolder.getContext().getUser().getId();
        User user = this.getById(userId);
        String oldMd5 = SaltUtil.md5Encrypt(oldPassword, user.getSalt());
        try {
            if (user.getPassword().equals(oldMd5)) {
                String newMd5 = SaltUtil.md5Encrypt(newPassword, user.getSalt());
                user.setPassword(newMd5);
                user.setUpdatePwdDate(new Date(System.currentTimeMillis()));
                this.updateById(user);
                return ResponseData.success();
            } else {
                return ResponseData.error(BizExceptionEnum.OLD_PWD_NOT_RIGHT.getMessage());
            }
        } finally {
            //触发
            UserListener.fireEvent(user);
        }

    }

    public Page<UserBean> selectUsersEx(UserBean userBean) {
        Page page = LayuiPageFactory.defaultPage();
        return this.baseMapper.query(page, userBean);
    }


    /**
     * 设置用户的角色
     *
     * @param userId:      用户id
     * @param roleIds：角色id
     * @return 结果
     */
    public int setRoles(Long userId, String roleIds) {
        UserRoleService userRoleService = BeanContextHolder.getBean(UserRoleService.class);
        userRoleService.setRoleUserAuthority(userId, roleIds);
        return this.baseMapper.setRoles(userId, roleIds);
    }

    /**
     * 通过账号获取用户
     *
     * @param account: 账号
     * @return 用户信息
     */
    public User getByAccount(String account) {
        return this.baseMapper.getByAccount(account);
    }


    public List<SysTreeNode> getSelectTreeData() {
        List<SysTreeNode> userTree = new ArrayList<>();
        QueryWrapper<Dept> deptQueryWrapper = new QueryWrapper<>();
        deptQueryWrapper.orderByAsc("sort");
        List<Dept> deptList = deptService.list(deptQueryWrapper);
        List<SysTreeNode> tmpUserList = new ArrayList<>();
        for (Dept dept : deptList) {
            userTree.add(SysTreeNode.changeDeptNode(dept, "optgroup"));
            tmpUserList = this.getUserTree(dept.getDeptId());
            if (tmpUserList.size() > 0) {
                userTree.addAll(tmpUserList);
            }
        }
        return userTree;
    }

    public List<SysTreeNode> getSelectTreeDataAllowLogin() {
        List<SysTreeNode> userTree = new ArrayList<>();
        QueryWrapper<Dept> deptQueryWrapper = new QueryWrapper<>();
        deptQueryWrapper.orderByAsc("sort");
        List<Dept> deptList = deptService.list(deptQueryWrapper);
        List<SysTreeNode> tmpUserList;
        for (Dept dept : deptList) {
            userTree.add(SysTreeNode.changeDeptNode(dept, "optgroup"));
            tmpUserList = this.getUserTreeAllowLogin(dept.getDeptId());
            if (tmpUserList.size() > 0) {
                userTree.addAll(tmpUserList);
            }
        }
        return userTree;
    }

    public List<SysTreeNode> getUserTree(Long deptId) {
        List<SysTreeNode> userTreeNode = new ArrayList<>();
        User user = new User();
        user.setDeptId(deptId);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("dept_id", deptId);
        userQueryWrapper.orderByAsc("create_time");
        List<User> userList = this.list(userQueryWrapper);
        for (User userT : userList) {
            userTreeNode.add(SysTreeNode.changeUserNode(userT));
        }
        return userTreeNode;
    }

    public List<SysTreeNode> getUserTreeAllowLogin(Long deptId) {
        List<SysTreeNode> userTreeNode = new ArrayList<>();
        User user = new User();
        user.setDeptId(deptId);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("dept_id", deptId);
        userQueryWrapper.ne("status", "DELETED");
        userQueryWrapper.orderByAsc("create_time");
        List<User> userList = this.list(userQueryWrapper);
        for (User userT : userList) {
            userTreeNode.add(SysTreeNode.changeUserNode(userT));
        }
        return userTreeNode;
    }


    /**
     * 获取用户的基本信息
     *
     * @param userId: 用户id
     * @return 结果
     */
    public Map<String, Object> getUserInfo(Long userId) {
        User user = this.getById(userId);
        Map<String, Object> map = UserFactory.removeUnSafeFields(user);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.putAll(map);
        //替换获取用户角色
        UserRoleService userRoleService = BeanContextHolder.getBean(UserRoleService.class);
        List<Long> roleList = userRoleService.getRoleList(user.getUserId());
        hashMap.put("roleName", ConstantFactory.me().getRoleNameEx(roleList));
        hashMap.put("deptName", ConstantFactory.me().getDeptName(user.getDeptId()));
        return hashMap;
    }


    public List<UserBean> query(UserBean userParam) {
        return baseMapper.query(userParam);
    }



    public LayuiPageInfo findPageBySpec(UserBean param) {
        Page pageContext = LayuiPageFactory.defaultPage();
        IPage page = this.baseMapper.query(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }


    /**
     * 用户选择查询
     *
     * @param userParam：查询条件
     * @return 结果
     */
    public List<Map<String, Object>> selectChooseList(UserBean userParam) {
        List<Map<String, Object>> dbList = this.baseMapper.queryMap(userParam);
        for (Map<String, Object> stringObjectMap : dbList) {
            String name = (String) stringObjectMap.get("name");
            String deptName = (String) stringObjectMap.get("deptName");
            stringObjectMap.put("showName", name + "(" + deptName + ")");
        }
        return dbList;
    }

    public void refreshCurrentUser() {

    }
}
